package
{	
	import flash.display.Sprite;
	
	import flash.display.Loader;
	
	import flash.events.Event;
	import flash.events.ProgressEvent;
	
	import flash.net.URLRequest;
	
	public class Preload extends Sprite
	{
		public var loadedObj:Array = new Array();
		private var itemsArray:Array = new Array();
		
		public var percLoad:int = 0;
		private var nbItem:int = 0;
		private var lding:int = 1;
		
		public function Preload(items:Array){
			itemsArray = items;
			nbItem = items.length;
			
			loadOne(lding - 1, itemsArray);
		}
		
		private function loadOne(n:int, items:Array):void{
			var ldr:Loader = new Loader();
			ldr.load(new URLRequest(items[n].toString()));
			ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
			ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
		}
		
		private function loadProgress(e:Event):void{
			var temp:int = Math.ceil((((e.target.bytesLoaded / e.target.bytesTotal)*100 * lding) / nbItem));
			if (temp > percLoad) percLoad = temp;
			dispatchEvent(new Event("preloadProgress")); // call the parent class with a progress update
		}
		
		private function loadComplete(e:Event):void{
			loadedObj.push(e.target.content);
			lding ++;
			if (loadedObj.length == nbItem) 
				dispatchEvent(new Event("preloadComplete"));
			else
				loadOne(lding - 1, itemsArray);
		}
		
		public function get percLoaded():int{
			return percLoad;
		}
		
		public function get objects():Array{
			return loadedObj;
		}
	}
}